<?php

namespace app\store\controller;

use app\admin\common\Base;
use app\admin\common\Excel;
use think\Db;

use app\store\model\Template as Model;
use app\store\model\TemplateDetails as ModelDetails;

use app\store\model\MakeOrder as ModelMakeOrder;
use app\store\model\MakeOrderDetails as ModelMakeOrderDetails;

//拆卸单
class Disassembly extends Base
{

    public function add()
    {
        $data = $this->request->param();
        $sn = osn('CXD', 5);

        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where('status', 0)->order('sort desc,id desc')->select();

        $this->assign('store', $store);
        $this->assign('sn', $sn);

        return $this->fetch();
    }


    public function index()
    {
        $data = $this->request->param();

        $this->assign('o_type', 9); //高级搜索状态（9：组装单记录、拆卸单记录）

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            //搜索
            if (isset($data['search'])) {

                if ($data['search'] == 0) {

                    $time1 = strtotime($data['datew']);
                    $time2 = strtotime($data['dateo']);

                    $sql = Db::name('make_order')->where('is_del', 0)->where('type', 1)->where('enterprise_id', $this->EnterpriseId);
                    $sql = !isset($time1) && !isset($time2) ? $sql : $sql->whereTime('addtime', 'between', [$time1, $time2]);
                    $sql = empty($data['matchCon']) ? $sql : $sql->where('sn|mark', $data['matchCon']);
                    $sql = empty($data['shenhezt']) ? $sql : $sql->where('status', $data['shenhezt']);
                    $list = $sql->order('id desc')->limit($start, $limit)->select();
                    $count = sizeof($list);

                    //高级搜索
                } else {

                    $time1 = strtotime($data['fromDate']);
                    $time2 = strtotime($data['toDate']);
                    $time3 = strtotime($data['fromDateCheck']);
                    $time4 = strtotime($data['toDateCheck']);

                    $tables = ['by', 'zh_by', 'store_id', 'check_user', 'status']; //主表字段查询
                    $keywork = [$data['usersCreatId'], $data['usersModifyId'], $data['store_id'], $data['usersChecksId'], $data['checkStatusId']];

                    //查询子表 
                    $sql = empty($data['childgoodsAutoId']) ? '' : db('make_order_details')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->where('goods_id', $data['childgoodsAutoId'])->column('pid');
                    //表查询方法    
                    $lists = Db::name('make_order')->where('is_del', 0)->where('type', 1)->where('enterprise_id', $this->EnterpriseId);
                    $lists = empty($time1) && empty($time2) ? $lists : $lists->where('check_time', 'between', [$time3, $time4]);
                    $lists = empty($time3) && empty($time4) ? $lists : $lists->where('check_time', 'between', [$time3, $time4]);
                    $lists = empty($data['remarkCon']) ? $lists : $lists->where('mark', 'like', '%' . $data['remarkCon'] . '%');
                    $lists = empty($sql) ? $lists : $lists->where('id', 'in', $sql);
                    //精确查询
                    for ($j = 0; $j < count($keywork); $j++) {
                        $lists = $keywork[$j] == '' ? $lists : $lists->where($tables[$j], $keywork[$j]);
                    }
                    $list = $lists->order('id desc')->limit($start, $limit)->select();
                    $count = sizeof($list);
                }
            } else {

                $list = Db::name('make_order')->where('type', 1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
                $count = Db::name('make_order')->where('type', 1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->count();
                // halt($list);
            }
            foreach ($list as $key => $value) {
                $list[$key]['addtime'] = date('Y-m-d', $value['addtime']);
                $goods = Db::name('goods')->where('id', $value['goods_id'])->find();
                $list[$key]['goods_name'] = $goods['sn'] . ' ' . $goods['name'] . '_' . $goods['model'];
                $list[$key]['unit_name'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
                $details = Db::name('make_order_details')->where('pid', $value['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
                $list[$key]['by'] = Db::name('auth_user')->where('id', $value['by'])->value('name');
                $list[$key]['check_user'] = $value['check_user'] != 0 ? Db::name('auth_user')->where('id', $value['check_user'])->value('name') : '';
                $list[$key]['check_time'] = $value['check_time'] == 0 ? '' : date('Y-m-d', $value['check_time']);
                foreach ($details as $k => $v) {
                    $details_goods = Db::name('goods')->where('id', $v['goods_id'])->find();
                    $details[$k]['goods_name'] = $details_goods['sn'] . ' ' . $details_goods['name'] . '_' . $details_goods['model'];
                    $details[$k]['unit_name'] = Db::name('unit')->where('id', $v['unit_id'])->value('name');
                    $details[$k]['dwcb'] = 0;
                    $details[$k]['cb'] = 0;
                }
                $list[$key]['son'] = $details;
            }

            return $this->grid_data($list, $count, $page, $limit);
        }

        return $this->fetch();
    }

    public function save()
    {
        $data = $this->request->param();
        // halt($data);
        $mark_order = [
            'addtime' => strtotime($data['addtime']),
            'money' => $data['money'],
            'sn' => $data['sn'],
            'by' => $this->Userinfo['id'],
            'zh_by' => $this->Userinfo['id'],
            'enterprise_id' => $this->EnterpriseId,
            'type' => 1
        ];

        $mark_order = array_merge($mark_order, $data['fixedGrid'][0]);
        // halt($mark_order);
        $model = new ModelMakeOrder();
        Db::startTrans();
        $res = $model->allowField(true)->save($mark_order);
        if (!$res) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        foreach ($data['grid'] as $key => $value) {
            $data['grid'][$key]['pid'] = $model->id;
            $data['grid'][$key]['enterprise_id'] = $this->EnterpriseId;
            unset($data['grid'][$key]['id']);
        }

        $modelDetails = new ModelMakeOrderDetails();
        $result = $modelDetails->allowField(true)->saveAll($data['grid']);
        if (!$result) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        Db::commit();
        return json(['status' => 1, 'msg' => '添加成功']);
    }

    public function edit()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            $list = Db::name('make_order')->where('id', $data['id'])->where('type', 1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            $count = Db::name('make_order')->where('id', $data['id'])->where('type', 1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->count();

            foreach ($list as $key => $value) {
                $list[$key]['addtime'] = date('Y-m-d', $value['addtime']);
                $goods = Db::name('goods')->where('id', $value['goods_id'])->find();
                $list[$key]['goodsname'] = $goods['sn'] . ' ' . $goods['name'] . '_' . $goods['model'];
                $list[$key]['dw'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
                $details = Db::name('make_order_details')->where('pid', $value['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
                $list[$key]['by'] = Db::name('auth_user')->where('id', $value['by'])->value('name');
                $list[$key]['check_user'] = $value['check_user'] != 0 ? Db::name('auth_user')->where('id', $value['check_user'])->value('name') : '';
                $list[$key]['check_time'] = $value['check_time'] == 0 ? '' : date('Y-m-d', $value['check_time']);
                $list[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
                $list[$key]['use_ck'] = get_stock($value['store_id'], $value['goods_id']);
                // halt($list);
                foreach ($details as $k => $v) {
                    $details_goods = Db::name('goods')->where('id', $v['goods_id'])->find();
                    $details[$k]['goodsname'] = $details_goods['sn'] . ' ' . $details_goods['name'] . '_' . $details_goods['model'];
                    $details[$k]['unit_name'] = Db::name('unit')->where('id', $v['unit_id'])->value('name');
                    $details[$k]['dwcb'] = 0;
                    $details[$k]['cb'] = 0;
                    $details[$k]['store_name'] = Db::name('store')->where('id', $v['store_id'])->value('name');
                    $details[$k]['use_ck'] = get_stock($v['store_id'], $v['goods_id']);
                }
                $list[$key]['son'] = $details;
            }
            // halt($list);
            return $this->grid_data($list, $count, $page, $limit);
        }

        $info = Db::name('make_order')->where('id', $data['id'])->find();
        $info['addtime'] = date('Y-m-d', $info['addtime']);
        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where('status', 0)->order('sort desc,id desc')->select();
        $this->assign('store', $store);
        $this->assign('info', $info);
        $this->assign('id', $data['id']);
        return $this->fetch();
    }

    public function shenhe()
    {
        $data = $this->request->param();
        $update = [
            'status' => $data['status'],
            'check_user' => $this->Userinfo['id'],
            'check_time' => time()
        ];
        $res = Db::name('make_order')->where('id', $data['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->update($update);
        if (!$res) {
            return json(['status' => 0, 'msg' => '操作失败']);
        }
        return json(['status' => 1, 'msg' => '操作成功']);
    }

    public function update()
    {
        $data = $this->request->param();
        $mark_order = [
            'addtime' => strtotime($data['addtime']),
            'money' => $data['money'],
            'sn' => $data['sn'],
            'zh_by' => $this->Userinfo['id'],
            'enterprise_id' => $this->EnterpriseId
        ];

        $mark_order = array_merge($mark_order, $data['fixedGrid'][0]);
        // halt($mark_order);
        $model = new ModelMakeOrder();
        Db::startTrans();
        $res = $model->allowField(true)->save($mark_order, ['id' => $data['id']]);
        if (!$res) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        $res1 = Db::name('make_order_details')->where('pid', $data['id'])->update(['is_del' => 1]);
        if (!$res1) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        foreach ($data['grid'] as $key => $value) {
            $data['grid'][$key]['pid'] = $data['id'];
            $data['grid'][$key]['enterprise_id'] = $this->EnterpriseId;
            unset($data['grid'][$key]['id']);
        }

        $modelDetails = new ModelMakeOrderDetails();
        $result = $modelDetails->allowField(true)->saveAll($data['grid']);
        if (!$result) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        Db::commit();
        return json(['status' => 1, 'msg' => '更新成功']);
    }

    public function template()
    {
        $data = $this->request->param();
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            $list = Db::name('template')->where('type', 1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($list as $key => $value) {
                $goods = Db::name('goods')->where('id', $value['goods_id'])->find();
                $list[$key]['templateName'] = $goods['sn'] . ' ' . $goods['name'] . '_' . $goods['model'];
                $details = Db::name('template_details')->where('pid', $value['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
                foreach ($details as $k => $v) {
                    $sonGoods = Db::name('goods')->where('id', $v['goods_id'])->find();
                    $list[$key]['sonName'][$k] = $sonGoods['sn'] . ' ' . $sonGoods['name'] . '_' . $sonGoods['model'];
                    $list[$key]['sonNum'][$k] = $v['number'];
                }
            }
            // halt($list);
            return $this->grid_data($list, count($list), $page, $limit);
        }
        return $this->fetch();
    }

    // 保存模板
    public function saveTemplate()
    {
        $data = $this->request->param();
        // $template = $data['data'][0];
        $template = [
            'name' => $data['name'],
            'addtime' => time(),
            'enterprise_id' => $this->EnterpriseId,
            'type' => $data['type']
        ];
        $template = array_merge($template, $data['data'][0]);

        $model = new Model();
        Db::startTrans();
        $res = $model->allowField(true)->save($template);
        if (!$res) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }
        foreach ($data['sonData'] as $key => $value) {
            $data['sonData'][$key]['pid'] = $model->id;
            $data['sonData'][$key]['enterprise_id'] = $this->EnterpriseId;
            unset($data['sonData'][$key]['id']);
        }

        $modelDetails = new ModelDetails();
        $result = $modelDetails->allowField(true)->saveAll($data['sonData']);
        if (!$result) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        Db::commit();
        return json(['status' => 1, 'msg' => '添加成功']);
    }

    public function export()
    {
        $data = $this->request->param();
        $rowid = explode(" ", $data['rowid']);
        $title = [
            'addtime' => '单据日期',
            'sn' => '单据编号',
            'goods_name' => '组合件',
            'number' => '组合件数量',
            'unit_name' => '单位',
            'son_goods_name' => '子件',
            'son_number' => '子件数量',
            'son_unit_name' => '单位',
            'son_dwcb' => '子件单位成本',
            'son_cb' => '子件成本',
            'by' => '制单人',
            'check_user' => '审核人',
            'check_time' => '审核日期',
            'mark' => '备注',
            'print_num' => '打印次数',
        ];

        $arr_list = [];
        $list = Db::name('make_order')->where('type', 1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        // halt($list);
        foreach ($list as $key => $value) {
            $list[$key]['addtime'] = date('Y-m-d', $value['addtime']);
            $goods = Db::name('goods')->where('id', $value['goods_id'])->find();
            $list[$key]['goods_name'] = $goods['sn'] . ' ' . $goods['name'] . '_' . $goods['model'];
            $list[$key]['unit_name'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
            $details = Db::name('make_order_details')->where('pid', $value['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            $list[$key]['by'] = Db::name('auth_user')->where('id', $value['by'])->value('name');
            $list[$key]['check_user'] = $value['check_user'] != 0 ? Db::name('auth_user')->where('id', $value['check_user'])->value('name') : '';
            $list[$key]['check_time'] = $value['check_time'] == 0 ? '' : date('Y-m-d', $value['check_time']);

            foreach ($details as $k => $v) {
                $details_goods = Db::name('goods')->where('id', $v['goods_id'])->find();
                $list[$key]['son_goods_name'] = $details_goods['sn'] . ' ' . $details_goods['name'] . '_' . $details_goods['model'];
                $list[$key]['son_unit_name'] = Db::name('unit')->where('id', $v['unit_id'])->value('name');
                $list[$key]['son_dwcb'] = 0;
                $list[$key]['son_cb'] = 0;
                $list[$key]['son_number'] = $v['number'];
                array_push($arr_list, $list[$key]);
            }
            $zh = [
                'addtime' => '',
                'sn' => $value['sn'],
                'goods_name' => '',
                'number' => '',
                'unit_name' => '',
                'son_goods_name' => '合计',
                'son_number' => array_sum(array_column($details, 'number')),
                'son_unit_name' => '',
                'son_dwcb' => array_sum(array_column($details, 'son_dwcb')),
                'son_cb' => array_sum(array_column($details, 'son_cb')),
                'by' => '',
                'check_user' => '',
                'check_time' => '',
                'mark' => '',
                'print_num' => ''
            ];
            array_push($arr_list, $zh);
        }
        // halt($arr_list);
        // array_push($arr_list, $zh);
        // halt($arr_list);
        // array_multisort($distance, SORT_DESC, $arr_list);//按照ID大小排序
        //添加标题到数组头部
        array_unshift($arr_list, $title);
        $kong_arr = $title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1] = '';
        }
        for ($i = 0; $i < 3; $i++) {
            array_unshift($arr_list, $kong_arr);
        }
        //根据此参数获取数据中的值，要与表格标题键名对应
        $keys = [];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }
        $merge = [];
        $options = [];
        $o_type = -1;
        $merge = [ //合并
            'start' => 5,
            'arr_zimu' => ['A', 'B', 'C', 'D', 'E', 'K', 'L', 'M', 'N', 'O'],
            'keyword' => 'sn',
        ];
        $options = [
            'alignCenter' => ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'], //居中
            'bold' => ['A1:O3', 'A4:O4'], //加粗
            'fontSize' => ['zimu' => ['A1'], 'size' => 20], //字体大小
        ];
        $title = [ //标题
            'title' => "拆卸单记录",
            'max_zimu' => "O",
            'number' => '3',
        ];
        $excel_export_title = "拆卸单记录_" . date('Y-m-d_His') . '.xlsx'; //文件名称
        $excel = new Excel();
        $excel->exportExcel($arr_list, $keys, $excel_export_title, $options, $o_type, $merge, $title);

        exit();
    }
}
